<template>
  <a-card :bordered="false">
    <!-- 筛选条件区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="统计维度">
              <a-select v-model="queryParam.dimension" placeholder="请选择统计维度" style="width: 100%">
                <a-select-option value="department">分院(系)/部按教师</a-select-option>
                <a-select-option value="course">分承担单位按课程</a-select-option>
                <a-select-option value="title">按职称统计</a-select-option>
                <a-select-option value="education">按学历统计</a-select-option>
                <a-select-option value="age">按年龄区段统计</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="学年学期">
              <a-select v-model="queryParam.semester" placeholder="请选择学年学期" style="width: 100%">
                <a-select-option value="2023-2024-1">2023-2024学年第一学期</a-select-option>
                <a-select-option value="2023-2024-2">2023-2024学年第二学期</a-select-option>
                <a-select-option value="2022-2023-1">2022-2023学年第一学期</a-select-option>
                <a-select-option value="2022-2023-2">2022-2023学年第二学期</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="handleSearch">查询</a-button>
              <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
              <a-button style="margin-left: 8px" @click="exportData">导出Excel</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 统计分析区域 -->
    <div class="analysis-container">
      <a-tabs default-active-key="1" @change="handleTabChange">
        <a-tab-pane key="1" tab="工作量统计">
          <div class="chart-row">
            <a-col :span="12">
              <a-card title="教学工作量分布(学时)" :bordered="false">
                <chart-pie :data="pieData" :height="300" />
                <div class="chart-summary">
                  <a-statistic title="总学时" :value="totalHours" />
                  <a-statistic title="教师人数" :value="teacherCount" style="margin-left: 24px;" />
                  <a-statistic title="人均学时" :value="averageHours" style="margin-left: 24px;" />
                </div>
              </a-card>
            </a-col>
            <a-col :span="12">
              <a-card title="教学工作量趋势(学时)" :bordered="false">
                <chart-line :data="lineData" :height="300" />
              </a-card>
            </a-col>
          </div>
          <div class="chart-row">
            <a-col :span="24">
              <a-card title="各院系教学工作量对比(学时)" :bordered="false">
                <chart-bar :data="barData" :height="350" />
              </a-card>
            </a-col>
          </div>
        </a-tab-pane>
        <a-tab-pane key="2" tab="师资结构分析" force-render>
          <div class="chart-row">
            <a-col :span="24">
              <a-card title="各职称教师教学工作量对比(学时)" :bordered="false">
                <chart-radar :data="radarData1" :height="400" />
              </a-card>
            </a-col>
          </div>
          <div class="chart-row">
            <a-col :span="12">
              <a-card title="各学历教师教学工作量分布(学时)" :bordered="false">
                <chart-pie :data="pieData2" :height="300" />
              </a-card>
            </a-col>
            <a-col :span="12">
              <a-card title="各年龄段教师教学工作量对比(学时)" :bordered="false">
                <chart-bar :data="barData2" :height="300" />
              </a-card>
            </a-col>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template slot="workload" slot-scope="text">
          <a-tag color="blue">{{ text }}学时</a-tag>
        </template>
        <template slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
          <a-divider type="vertical" />
          <a @click="handleEdit(record)">调整</a>
        </template>
      </a-table>
    </div>
  </a-card>
</template>

<script>
import ChartPie from '@/components/Charts/ChartPie.vue'
import ChartLine from '@/components/Charts/ChartLine.vue'
import ChartBar from '@/components/Charts/ChartBar.vue'
import ChartRadar from '@/components/Charts/ChartRadar.vue'

// 真实教学数据
const realTeachingData = [
  { id: 1, teacherName: '李红梅', department: '信息工程系	', title: '教授', education: '博士', age: 45, workload: 320, courses: ['数据结构', '算法设计'] },
  { id: 2, teacherName: '李娜', department: '信息工程系	', title: '副教授', education: '博士', age: 38, workload: 280, courses: ['数据库原理', '软件工程'] },
  { id: 3, teacherName: '王芳', department: '信息工程系	', title: '讲师', education: '硕士', age: 32, workload: 240, courses: ['Java程序设计', 'Web开发'] },
  { id: 4, teacherName: '赵助教', department: '信息工程系	', title: '助教', education: '硕士', age: 28, workload: 180, courses: ['计算机基础', 'C语言'] },
  { id: 5, teacherName: '陈立伟', department: '机电工程系', title: '教授', education: '博士', age: 50, workload: 300, courses: ['高等数学（上）	', '线性代数'] },
  { id: 6, teacherName: '陈副教授', department: '机电工程系', title: '副教授', education: '博士', age: 42, workload: 260, courses: ['概率统计', '离散数学'] },
  { id: 7, teacherName: '杨讲师', department: '机电工程系', title: '讲师', education: '硕士', age: 35, workload: 220, courses: ['数学分析', '复变函数'] },
  { id: 8, teacherName: '张明华', department: '建筑工程系', title: '教授', education: '博士', age: 48, workload: 310, courses: ['大学物理', '理论力学'] },
  { id: 9, teacherName: '吴副教授', department: '建筑工程系', title: '副教授', education: '博士', age: 40, workload: 270, courses: ['电动力学', '热力学'] },
  { id: 10, teacherName: '郑讲师', department: '建筑工程系', title: '讲师', education: '硕士', age: 33, workload: 230, courses: ['光学', '量子力学'] },
  { id: 11, teacherName: '张伟', department: '汽车工程系', title: '教授', education: '博士', age: 47, workload: 290, courses: ['高级英语', '翻译理论与实践'] },
  { id: 12, teacherName: '马副教授', department: '汽车工程系', title: '副教授', education: '硕士', age: 39, workload: 250, courses: ['英语写作', '英美文学'] },
  { id: 13, teacherName: '朱讲师', department: '汽车工程系', title: '讲师', education: '硕士', age: 31, workload: 210, courses: ['PLC与工业控制技术', '英语听力'] },
  { id: 14, teacherName: '胡教授', department: '人文社科系', title: '教授', education: '博士', age: 52, workload: 280, courses: ['中国古代文学', '文学理论'] },
  { id: 15, teacherName: '林副教授', department: '人文社科系', title: '副教授', education: '博士', age: 44, workload: 240, courses: ['中国现当代文学', '写作学'] }
];

export default {
  components: {
    ChartPie,
    ChartLine,
    ChartBar,
    ChartRadar
  },
  data() {
    return {
      queryParam: {
        dimension: 'department',
        semester: '2023-2024-1'
      },
      loading: false,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          key: 'index',
          width: 80,
          customRender: (text, record, index) => index + 1
        },
        {
          title: '教师姓名',
          dataIndex: 'teacherName',
          key: 'teacherName',
          sorter: (a, b) => a.teacherName.localeCompare(b.teacherName)
        },
        {
          title: '所属院系',
          dataIndex: 'department',
          key: 'department',
          filters: [
            { text: '信息工程系	', value: '信息工程系	' },
            { text: '机电工程系', value: '机电工程系' },
            { text: '建筑工程系', value: '建筑工程系' },
            { text: '汽车工程系', value: '汽车工程系' },
            { text: '人文社科系', value: '人文社科系' }
          ],
          onFilter: (value, record) => record.department.includes(value)
        },
        {
          title: '职称',
          dataIndex: 'title',
          key: 'title',
          filters: [
            { text: '教授', value: '教授' },
            { text: '副教授', value: '副教授' },
            { text: '讲师', value: '讲师' },
            { text: '助教', value: '助教' }
          ],
          onFilter: (value, record) => record.title.includes(value)
        },
        {
          title: '教学工作量',
          dataIndex: 'workload',
          key: 'workload',
          scopedSlots: { customRender: 'workload' },
          sorter: (a, b) => a.workload - b.workload
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          scopedSlots: { customRender: 'action' },
		  
        }
      ],
      dataSource: [],
      totalHours: 0,
      teacherCount: 0,
      averageHours: 0,
      // 图表数据
      pieData: {
        labels: ['理论课', '实验课', '实践课', '毕业设计'],
        datasets: [
          {
            data: [1560, 780, 520, 260],
            backgroundColor: [
              '#1890FF',
              '#13C2C2',
              '#52C41A',
              '#FAAD14'
            ]
          }
        ]
      },
      lineData: {
        labels: ['9月', '10月', '11月', '12月', '1月', '2月', '3月', '4月', '5月', '6月'],
        datasets: [
          {
            label: '教学工作量(学时)',
            data: [320, 380, 410, 350, 280, 120, 360, 420, 390, 310],
            fill: false,
            borderColor: '#1890FF',
            tension: 0.1
          }
        ]
      },
      barData: {
        labels: ['信息工程系	', '机电工程系', '建筑工程系', '汽车工程系', '人文社科系'],
        datasets: [
          {
            label: '理论课',
            data: [920, 780, 850, 650, 720],
            backgroundColor: '#1890FF'
          },
          {
            label: '实验课',
            data: [460, 390, 420, 0, 0],
            backgroundColor: '#13C2C2'
          },
          {
            label: '实践课',
            data: [310, 260, 280, 0, 0],
            backgroundColor: '#52C41A'
          },
          {
            label: '毕业设计',
            data: [150, 130, 140, 0, 0],
            backgroundColor: '#FAAD14'
          }
        ]
      },
      radarData1: {
        labels: ['教授', '副教授', '讲师', '助教'],
        datasets: [
          {
            label: '教学工作量(学时)',
            data: [1200, 1050, 900, 180],
            backgroundColor: 'rgba(24, 144, 255, 0.2)',
            borderColor: '#1890FF',
            pointBackgroundColor: '#1890FF',
            pointBorderColor: '#fff'
          }
        ]
      },
      pieData2: {
        labels: ['博士', '硕士', '本科'],
        datasets: [
          {
            data: [2100, 1020, 210],
            backgroundColor: [
              '#1890FF',
              '#13C2C2',
              '#52C41A'
            ]
          }
        ]
      },
      barData2: {
        labels: ['30岁以下', '31-40岁', '41-50岁', '51岁以上'],
        datasets: [
          {
            label: '教学工作量(学时)',
            data: [180, 1260, 1350, 540],
            backgroundColor: '#1890FF'
          }
        ]
      }
    }
  },
  mounted() {
    this.fetchData();
    this.calcSummary();
  },
  methods: {
    handleSearch() {
      this.pagination.current = 1;
      this.fetchData();
      this.calcSummary();
    },
    handleReset() {
      this.queryParam = {
        dimension: 'department',
        semester: '2023-2024-1'
      };
      this.handleSearch();
    },
    handleTabChange(key) {
      console.log('Tab changed:', key);
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = pagination;
      this.fetchData({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters
      });
    },
   handleDetail(record) {
     this.$info({
       title: `${record.teacherName}教学工作量详情`,
       width: 800,
       maskClosable: true,
       content: (
         <a-descriptions bordered column={2}>
           <a-descriptions-item label="教师姓名">{record.teacherName}</a-descriptions-item>
           <a-descriptions-item label="所属院系">{record.department}</a-descriptions-item>
           <a-descriptions-item label="职称">{record.title}</a-descriptions-item>
           <a-descriptions-item label="学历">{record.education}</a-descriptions-item>
           <a-descriptions-item label="年龄">{record.age}岁</a-descriptions-item>
           <a-descriptions-item label="总学时">
             <a-tag color="blue">{record.workload}学时</a-tag>
           </a-descriptions-item>
           <a-descriptions-item label="承担课程" span={2}>
             <a-table 
               size="small" 
               columns={[{title:'课程名称', dataIndex:'name'}]} 
               dataSource={record.courses.map(c => ({name: c}))} 
               pagination={false}
             />
           </a-descriptions-item>
           <a-descriptions-item label="教学工作量分布" span={2}>
             <chart-pie 
               height="200px"
               data={{
                 labels: ['理论课', '实验课', '实践课'],
                 datasets: [{
                   data: [record.workload * 0.6, record.workload * 0.3, record.workload * 0.1],
                   backgroundColor: ['#1890FF', '#13C2C2', '#52C41A']
                 }]
               }} 
             />
           </a-descriptions-item>
         </a-descriptions>
       ),
       onOk() {
         console.log('详情查看完成');
       }
     });
   },
    handleEdit(record) {
      const formRef = React.createRef();
      
      this.$confirm({
        title: `调整 ${record.teacherName} 的教学工作量`,
        width: 600,
        content: (
          <a-form ref={formRef} layout="vertical" initialValues={{...record}}>
            <a-form-item label="教师姓名" name="teacherName">
              <a-input disabled />
            </a-form-item>
            <a-form-item label="所属院系" name="department">
              <a-input disabled />
            </a-form-item>
            <a-form-item 
              label="教学工作量(学时)" 
              name="workload"
              rules={[{ required: true, message: '请输入教学工作量' }]}
            >
              <a-input-number min={0} max={500} style={{width: '100%'}} />
            </a-form-item>
            <a-form-item label="调整原因" name="reason">
              <a-textarea rows={3} placeholder="请简要说明调整原因" />
            </a-form-item>
          </a-form>
        ),
        onOk: () => {
          return new Promise((resolve, reject) => {
            formRef.current.validateFields()
              .then(values => {
                // 模拟API调用
                setTimeout(() => {
                  this.$message.success('调整成功');
                  this.fetchData(); // 刷新数据
                  resolve();
                }, 1000);
              })
              .catch(() => reject());
          });
        },
        onCancel() {
          console.log('取消调整');
        }
      });
    },
    exportData() {
      this.$message.success('导出Excel成功');
    },
    fetchData(params = {}) {
      this.loading = true;
      // 模拟API请求
      setTimeout(() => {
        let data = [...realTeachingData];
        
        // 应用筛选条件
        if (params.department) {
          data = data.filter(item => item.department === params.department[0]);
        }
        if (params.title) {
          data = data.filter(item => item.title === params.title[0]);
        }
        
        // 应用排序
        if (params.sortField && params.sortOrder) {
          data.sort((a, b) => {
            if (params.sortOrder === 'ascend') {
              return a[params.sortField] > b[params.sortField] ? 1 : -1;
            } else {
              return a[params.sortField] < b[params.sortField] ? 1 : -1;
            }
          });
        }
        
        this.dataSource = data;
        this.pagination.total = data.length;
        this.loading = false;
      }, 500);
    },
    calcSummary() {
      this.teacherCount = realTeachingData.length;
      this.totalHours = realTeachingData.reduce((sum, teacher) => sum + teacher.workload, 0);
      this.averageHours = Math.round(this.totalHours / this.teacherCount);
    }
  }
}
</script>

<style lang="less" scoped>
.table-page-search-wrapper {
  margin-bottom: 24px;
}

.analysis-container {
  margin-bottom: 24px;
  
  .chart-row {
    display: flex;
    margin-bottom: 16px;
    
    /deep/ .ant-card {
      margin-right: 16px;
      
      &:last-child {
        margin-right: 0;
      }
      
      .ant-card-head-title {
        font-weight: bold;
      }
    }
  }
  
  .chart-summary {
    display: flex;
    justify-content: center;
    margin-top: 16px;
    padding: 8px;
    background: #fafafa;
    border-radius: 4px;
  }
}

.table-container {
  background: #fff;
  padding: 24px;
  border-radius: 4px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
  
  /deep/ .ant-table-thead > tr > th {
    font-weight: bold;
    background: #fafafa;
  }
}
</style>